package com.hluck.mvidemo.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hluck.mvidemo.data.intent.MainIntent
import com.hluck.mvidemo.data.repository.MainRepository
import com.hluck.mvidemo.data.state.MainState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 *
 * @Author： LJH
 * @Time： 2023/10/9
 * @description：
 */
class MainViewModel(private val repository: MainRepository): ViewModel() {

    val mainIntentChannel = Channel<MainIntent>(Channel.UNLIMITED)

    private val _state = MutableStateFlow<MainState>(MainState.Idle)

    val state:StateFlow<MainState> get() = _state

    init {
        viewModelScope.launch {
            mainIntentChannel.consumeAsFlow().collect{
                when(it){
                    is MainIntent.GetWallpaper -> getWallpapers()
                }
            }
        }
    }

    /**
     * 获取壁纸
     */
    private fun getWallpapers(){
        viewModelScope.launch {
            _state.value = MainState.Loading
            _state.value = try {
                MainState.Wallpapers(repository.getWallpaper())
            } catch (e:Exception){
                MainState.Error(e.localizedMessage ?: "UnKnow Error")
            }
        }
    }
}